//  时间格式
export const nowTime = (type, date = "") => {
  if (date) {
    date.length === 13 ? date : date * 1000
  }
  let now = new Date(date ? date : new Date())
  let year = now.getFullYear()
  let month = now.getMonth() + 1 //真实的月份需要再加上1
  let day = now.getDate()
  let h = now.getHours()
  let m = now.getMinutes()
  let s = now.getSeconds()

  if (type == 1) {
    // 年月日
    return `${year}-${month.length == 2 ? month : "0" + month}-${
      day.length == 2 ? day : "0" + day
    }`
  }
  if (type == 2) {
    // 年月日 时分秒
    return `${year}-${month.length == 2 ? month : "0" + month}-${
      day.length == 2 ? day : "0" + day
    } ${h}:${m}:${s}`
  }
  if (type == 3) {
    // 时分秒
    return `$${h}:${m}:${s}`
  }
  if ((type = 4)) {
    // 周几
    const weekArr = [
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六",
      "星期天",
    ]
    const week = weekArr[date.getDay()]
    return week
  }
}

//校验姓名
export const isName = (name) => {
  var rgx = /^[\u4e00-\u9fa5]+|[A-Za-z]+|[\u4e00-\u9fa5]+$/
  if (!rgx.test(name)) {
    showToast({
      title: "姓名不合法",
      icon: "none",
    })
    return false
  }
  return true
}

//  校验手机号
export const isPhone = (phone) => {
  const re = /^1[0-9]{10}$/
  if (phone.length === 11) {
    if (!re.test(phone)) {
      showToast({
        title: "手机号格式不正确！",
      })
      return false
    } else {
      return true
    }
  } else {
    showToast({
      title: "手机号长度不对！",
    })
    return false
  }
}

export const showToast = (params) => {
  uni.showToast({
    title: params.title,
    icon: params.icon || "none",
    mask: params.mask || false,
  })
}

// 模态框
export const showModal = (params) => {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title: params.title || "",
      content: params.content,
      confirmText: params.successText || "确定", // 确认按钮
      cancelText: params.failText || "取消", // 取消按钮
      showCancel: params.showCancel,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * @param {}
 * 防抖
 */
export const debounce = (fn, delay = 500) => {
  let timer = null
  return function() {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function() {
      fn.apply(this.arguments)
      timer = null
    }, delay)
  }
}

export const formatTime = (params) => {
  const date = new Date(params)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return `${[year, month, day].map(formatNumber).join('/')} ${[
		hour,
		minute,
		second
	]
		.map(formatNumber)
		.join(':')}`
}
const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
